/**   
 * @Title: CommonWebView.java 
 * @author 7828wc   
 * @date 2016年1月21日 下午4:15:17 
 */
package com.onstar.cn.common.jsBridge;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.onstar.cn.common.R;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.SizeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/**
 * @author 7828wc
 *
 */
public class CommonWebView extends WebView {
	private static final String TAG = "CommonWebView";

	private Context mContext;
	// 长按查看图片
	private ItemLongClickedPopWindow itemLongClickedPopWindow;
	// 手指触发屏幕的坐标
	private int downX, downY;
	// 需要保存图片的路径
	private String saveImgUrl = "";

	/**
	 * @param context
	 * @param attrs
	 * @param defStyle
	 */
	public CommonWebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initData(this, context);
	}

	/**
	 * @param context
	 * @param attrs
	 */
	public CommonWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initData(this, context);
	}

	/**
	 * @param context
	 */
	public CommonWebView(Context context) {
		super(context);
		initData(this, context);
	}


public void setLongClickListener(WebView mWebView, final Context mContext){
	mWebView.setOnTouchListener(listener);

	mWebView.setOnLongClickListener(new View.OnLongClickListener() {
		@Override
		public boolean onLongClick(View v) {
			WebView.HitTestResult result = ((WebView)v).getHitTestResult();
			if (null == result)
				return false;
			int type = result.getType();
			if (type == WebView.HitTestResult.UNKNOWN_TYPE)
				return false;
			if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {

			}

			itemLongClickedPopWindow = new ItemLongClickedPopWindow(mContext,
					ItemLongClickedPopWindow.IMAGE_VIEW_POPUPWINDOW,
					SizeUtil.dp2px(mContext, 120), SizeUtil.dp2px(mContext,45));

			switch (type) {
				case WebView.HitTestResult.PHONE_TYPE: // 处理拨号
					break;
				case WebView.HitTestResult.EMAIL_TYPE: // 处理Email
					break;
				case WebView.HitTestResult.GEO_TYPE: // TODO
					break;
				case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
					break;
				case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
					break;
				case WebView.HitTestResult.IMAGE_TYPE: // 处理长按图片的菜单项
					// 获取图片的路径
					saveImgUrl = result.getExtra();
					//通过GestureDetector获取按下的位置，来定位PopWindow显示的位置
//					itemLongClickedPopWindow.showAtLocation();
					itemLongClickedPopWindow.showAtLocation(v, Gravity.TOP | Gravity.LEFT, downX, downY + SizeUtil.dp2px(mContext,45));
//					itemLongClickedPopWindow.showAsDropDown(v,downX, downY +10);
//					itemLongClickedPopWindow.showAsDropDown(v);
					break;
				default:
					break;
			}

//			itemLongClickedPopWindow.getView(R.id.item_longclicked_viewImage)
//					.setOnClickListener(new View.OnClickListener() {
//						@Override
//						public void onClick(View v) {
////							itemLongClickedPopWindow.dismiss();
////							Intent intent = new Intent(mContext, ShowImgActivity.class);
////							intent.putExtra("info", saveImgUrl);
////							startActivity(intent);
//						}
//					});
			itemLongClickedPopWindow.getView(R.id.item_longclicked_saveImage)
					.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							itemLongClickedPopWindow.dismiss();
							new SaveImage().execute(); // Android 4.0以后要使用线程来访问网络
						}
					});
			return true;
		}
	});


}

	View.OnTouchListener listener = new View.OnTouchListener() {

		@Override
		public boolean onTouch(View arg0, MotionEvent arg1) {
			downX = (int) arg1.getX();
			downY = (int) arg1.getY();
			return false;
		}
	};

/***
 * 功能：用线程保存图片
 *
 * @author wangyp
 */
private class SaveImage extends AsyncTask<String, Void, String> {
	@Override
	protected String doInBackground(String... params) {
		String result = "";
		try {
			String sdcard = Environment.getExternalStorageDirectory().toString();
			File file = new File(sdcard + "/Download");
			if (!file.exists()) {
				file.mkdirs();
			}
			int idx = saveImgUrl.lastIndexOf(".");
			String ext = saveImgUrl.substring(idx);
			file = new File(sdcard + "/Download/" + new Date().getTime() + ext);
			InputStream inputStream = null;
			URL url = new URL(saveImgUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(20000);
			if (conn.getResponseCode() == 200) {
				inputStream = conn.getInputStream();
			}
			byte[] buffer = new byte[4096];
			int len = 0;
			FileOutputStream outStream = new FileOutputStream(file);
			while ((len = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			outStream.close();
			result = "图片已保存至：" + file.getAbsolutePath();

//			Intent localIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
//			final Uri localUri = Uri.fromFile(file);
//			localIntent.setData(localUri);
//			sendBroadcast(localIntent);
		} catch (Exception e) {
			result = "保存失败！" + e.getLocalizedMessage();
		}
		return result;
	}

	@Override
	protected void onPostExecute(String result) {
		Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
	}
}

	public void setupMySettings() {
		WebSettings webSettings = this.getSettings();
		webSettings.setLoadWithOverviewMode(false);
		webSettings.setUseWideViewPort(false);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(false);
		webSettings.setAppCacheEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		webSettings.setDomStorageEnabled(true);
		webSettings.setDatabaseEnabled(true);
		webSettings.setGeolocationEnabled(true);
//		webSettings.setBlockNetworkImage(false);//解决图片不显示
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
			webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
	}

	@SuppressLint("NewApi")
	public void setupDefaultSettings(WebView webview, Context context) {
		// WebSettingManager wsm = WebSettingManager.getInstance();
		WebSettings settings = webview.getSettings();
		// settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		// settings.setCacheMode(WebSettings.LOAD_NORMAL);

		settings.setLightTouchEnabled(false);
		settings.setNeedInitialFocus(false);

		// settings.setLoadsImagesAutomatically(wsm.getIsLoadImage());
		settings.setJavaScriptEnabled(true);

		settings.setSupportZoom(false);
		settings.setBuiltInZoomControls(false);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			settings.setDisplayZoomControls(false);
		} else {

		}
		settings.setDefaultTextEncodingName("UTF-8");
		settings.setLoadWithOverviewMode(true);
		settings.setUseWideViewPort(true);

		settings.setRenderPriority(WebSettings.RenderPriority.NORMAL);

		settings.setGeolocationEnabled(true);
		settings.setDatabaseEnabled(true);
		settings.setDomStorageEnabled(true);
		settings.setAppCacheEnabled(true);

		// long appCacheMaxSize =
		// UmeBrowserActivity.myself.getWebStorageSizeManagerInstance().getAppCacheMaxSize();
		String databasePath = context.getDir("databases", 0).getPath();
		String geolocationDatabasePath = context.getDir("geolocation", 0).getPath();
		String appCachePath = context.getDir("appcache", 0).getPath();

		settings.setGeolocationDatabasePath(geolocationDatabasePath);
		settings.setDatabasePath(databasePath);
		// settings.setAppCacheMaxSize(appCacheMaxSize);
		settings.setAppCachePath(appCachePath);
		settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
		settings.setSavePassword(true);
		settings.setSaveFormData(true);

		// settings.setPageCacheCapacity(10);
		reflectPageCacheTo(settings, 20);
		// settings.setUserAgentString(wsm.getUAString());
		settings.setSupportMultipleWindows(true);

		settings.setJavaScriptCanOpenWindowsAutomatically(true);

		// reflectPrivateBrowsingEnable(settings,
		// wsm.getPrivateBrowsingEnable());

//		 settings.setTextSize(mapIntToTextSize(wsm.getTextSize()));
//		 mapTextSizeToZoom(webview, mapIntToTextSize(wsm.getTextSize()));

		// Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated
		// entirely for Jellybean 4.2)
		try {
			Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", boolean.class);

			String manufacturer = Build.MANUFACTURER;
			Log.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
					&& Build.MANUFACTURER.contains("HTC")) {
				gingerbread_getMethod.invoke(settings, true);
			}
		} catch (NoSuchMethodException e) {
			Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8");
		} catch (IllegalArgumentException e) {
			Log.d(TAG, "Doing the NavDump failed with bad arguments");
		} catch (IllegalAccessException e) {
			Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore");
		} catch (InvocationTargetException e) {
			Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore.");
		}
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
			settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
	}

	private void reflectPageCacheTo(WebSettings setting, int capacity) {
		try {
			Method setpgcache = setting.getClass().getDeclaredMethod("setPageCacheCapacity", int.class);
			setpgcache.setAccessible(true);
			setpgcache.invoke(setting, capacity);
		} catch (NoSuchMethodException e) {
			LogManager.getInstance().e(e.getMessage());
		} catch (IllegalArgumentException e) {
			LogManager.getInstance().e(e.getMessage());
		} catch (IllegalAccessException e) {
			LogManager.getInstance().e(e.getMessage());
		} catch (InvocationTargetException e) {
			LogManager.getInstance().e(e.getMessage());
		}
	}

	private void initData(WebView webView,Context context) {
		mContext = context;
		setupDefaultSettings(webView,context);
		setLongClickListener(webView,context);
	}
}
